package com.jy.admin.jobs;

import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.TimeUtils;
import com.jsoniter.output.JsonStream;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.CeCommentPushLogDao;
import com.jy.admin.db.dao.CeOrdersDao;
import com.jy.admin.db.dao.ClCommentDao;
import com.jy.admin.db.entity.CeCommentPushLogEntity;
import com.jy.admin.db.entity.CeOrdersEntity;
import com.jy.admin.db.entity.ClCommentEntity;
import com.robert.vesta.util.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/7
 * Time: 3:16 下午
 */
@Service
public class SyncCommentsJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(SyncCommentsJob.class);


    @Autowired
    private ClCommentDao clCommentDao;

    @Autowired
    private ApolloConfigUtil configUtil;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeOrdersDao ordersDao;


    @Scheduled(fixedDelay = 1000L * 60)
    public void syncComment() {
        LOGGER.info("== 开始同步催记 ==");
        if (!configUtil.getCommentSyncSwitch()) {
            LOGGER.info("== 开始同步催记 开关未开启==");
            return;
        }
        String hostIp = IpUtils.getHostIp();
        LOGGER.info("==开始同步催记==,ip:{}", hostIp);

        if (!hostIp.equals(configUtil.getJobRunIp())) {
            LOGGER.info("==开始同步催记==, 当前机器ip不是job执行机器,当前iP:{},目标IP:{}", hostIp, configUtil.getJobRunIp());
            return;
        }
        Page page = new Page();
        page.setPageSize(1000);
        List<ClCommentEntity> comments = clCommentDao.selectListBySyncStatusAndPage(0, page);

        if (CollectionUtils.isEmpty(comments)) {
            LOGGER.info("== 开始同步催记 size==0  ==");
            return;
        }
        LOGGER.info("== 开始同步催记  ==,size:{}", comments.size());

        comments.forEach(comment -> {
            String collectionNo = comment.getTradeNo();
            CeOrdersEntity order = ordersDao.getOneByCollectionNo(collectionNo);
            if (order == null) {
                clCommentDao.updateSyncStatusById(comment.getId().intValue(), 1);
                return;
            }
            Map<String, String> detail = new HashMap<>();
            detail.put("mobile", comment.getMobile());
            detail.put("relation", comment.getRelation());
            detail.put("calling_result", comment.getCallingResult());
            detail.put("promise_pay_date", DateUtil.getDateTime(comment.getPromisePayDate()));
            CeCommentPushLogEntity ceCommentPushLogEntity = new CeCommentPushLogEntity()
                    .setAgentCode(order.getAgentCode())
                    .setMerchantCode(order.getMerchantCode())
                    .setTargetType(comment.getType())
                    .setTargetMsg(comment.getContent())
                    .setStatus(0)
                    .setOriginNo(order.getOrderNo())
                    .setPushDetail(JsonStream.serialize(detail));
            commentPushLogDao.insert(ceCommentPushLogEntity);
            clCommentDao.updateSyncStatusById(comment.getId().intValue(), 1);
        });

        LOGGER.info("== 开始同步催记  同步完成==,size:{}", comments.size());
    }

    @Scheduled(fixedDelay = 1000L * 60)
    public void sendLog() {
        LOGGER.info("==sendLog 开始 composeNote 催记 ==");
        String hostIp = IpUtils.getHostIp();
        LOGGER.info("==sendLog PayCallBackToBizJob==,ip:{}", hostIp);

        if (!hostIp.equals(configUtil.getCommentRunIp())) {
            LOGGER.info("==sendLog PayCallBackToBizJob==, 当前机器ip不是job执行机器,当前iP:{},目标IP:{}", hostIp, configUtil.getJobRunIp());
            return;
        }
        Page page = new Page();
        page.setPageSize(500);
        List<CeCommentPushLogEntity> comments = commentPushLogDao.getListByStatus(0);
        if (CollectionUtils.isNotEmpty(comments)) {
            LOGGER.info("== sendLog 开始 composeNote 催记  composeNote==,size:{}", comments.size());
            comments.forEach(comment -> {
                if (!BaseJobHandler.merchantAndServiceMap.containsKey(comment.getMerchantCode())) {
                    LOGGER.error("== sendLog composeNote==,找不到商户的处理逻辑，merchant:{}", comment.getMerchantCode());
                    return;
                }
                LOGGER.info("==sendLog 开始composeNote催记 构造目标催记内容 composeNote ==,merchantCode:{}", comment.getMerchantCode());
                BaseJobHandler.merchantAndServiceMap.get(comment.getMerchantCode()).composeNote(comment);
            });

            LOGGER.info("== sendLogcomposeNote催记 composeNote 构造完成  准备发送催记内容到甲方 ==");
        }

        if (!configUtil.getCommentSendSwitch()) {
            LOGGER.info("==sendLog 开始send催记 开关未开启==");
            return;
        }

        List<CeCommentPushLogEntity> commentsNeedSend = commentPushLogDao.getListByStatus(1);
        if (CollectionUtils.isEmpty(commentsNeedSend)) {
            LOGGER.info("==sendLog 开始send催记 sendNote size==0  ==");
            return;
        }
        commentsNeedSend.forEach(comment -> {
            if (!BaseJobHandler.merchantAndServiceMap.containsKey(comment.getMerchantCode())) {
                LOGGER.error("== sendLog sendNote ==,找不到商户的处理逻辑，merchant:{}", comment.getMerchantCode());
                return;
            }
            LOGGER.info("==sendLog 开始send催记  sendNote ==,merchantCode:{}", comment.getMerchantCode());
            comment.setStatus(9);
            commentPushLogDao.updateByPrimaryKey(comment);

            boolean sendSuccess = false;
            try {
                CeOrdersEntity entity = ordersDao.getTodayOneByOrderNo(comment.getOriginNo());
                if (entity != null && (entity.getStatus() == 2 || entity.getStatus() == 3 || entity.getStatus() == 4)) {
                    LOGGER.info("==sendLog 已还款订单不发生催记==,orderNo:{}",comment.getOriginNo());
                    sendSuccess = true;
                } else {
                    sendSuccess = BaseJobHandler.merchantAndServiceMap.get(comment.getMerchantCode()).sendNote(comment);
                }
            } catch (Exception e) {
                LOGGER.info("==sendLog 发送催记失败  sendNote ==,merchantCode:{},e", comment.getMerchantCode(), e);
            }

            comment.setStatus(sendSuccess ? 2 : 3);
            commentPushLogDao.updateByPrimaryKey(comment);
        });

    }


    public static void main(String[] args) {
        int hour = DateUtil.getHour();

        System.err.println(hour);
    }
}
